<?php
defined('BASEPATH') or exit('No direct script access allowed');

require_once RESOURCE_PATH . 'php/PHPExcel/Classes/PHPExcel.php';
require_once RESOURCE_PATH . 'php/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';

class CreateExcel
{

    private $objPHPExcel;

    private $objWriter;
    
    public $file_name = 'resume';

    public function __construct()
    {
        $objPHPExcel = new PHPExcel();
        $this->objPHPExcel = $objPHPExcel;
    }

    /* 设置其属性 */
    public function setProperties($title, $content, $width = array())
    {
        $objPHPExcel = $this->objPHPExcel;
        /* 设置表头 */
        $SerialNumber = ord('A');
        $count = count($title);
        $rowNumber = 1;
        foreach ($title as $k => $v) {
            $widthVal = empty($width[$k])?20:$width[$k];
            $serial = chr($k + $SerialNumber) . $rowNumber;
            $objPHPExcel->getActiveSheet()
                ->getColumnDimension(rtrim($serial, $rowNumber))
                ->setWidth($widthVal);
            $objPHPExcel->getActiveSheet()->setCellValue($serial, $v);
        }
        /* 设置值 */
        foreach ($content as $key => $value) {
            $rowNumber ++;
            foreach ($value as $k => $v) {
                $serial = chr($k + $SerialNumber) . $rowNumber;
                $objPHPExcel->getActiveSheet()->setCellValue($serial, $v);
            }
        }
    }

    /* 获取excel表格 */
    public function getExcel($type)
    {
        switch ($type) {
            case 'explorer':
                $this->outputToExplorer();
                break;
            case 'file':
                break;
            default:
                $this->outputToExplorer();
                break;
        }
    }

    /* 设置头信息，直接输出到浏览器 */
    private function outputToExplorer()
    {
        $objWriter = new PHPExcel_Writer_Excel5($this->objPHPExcel);
        ob_end_clean(); // 清除缓冲区,避免乱码
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename="'.$this->file_name.'.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }
}